package com.fanxuankai.boot.jenkins.autoconfigure;

import com.fanxuankai.boot.jenkins.component.JenkinsItemSynchronizer;
import com.offbytwo.jenkins.JenkinsServer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author fanxuankai
 */
@Configuration
@EnableConfigurationProperties({JenkinsProperties.class, JenkinsSyncProperties.class})
public class JenkinsAutoConfiguration {
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty({JenkinsProperties.SERVICE_URI, JenkinsProperties.USERNAME, JenkinsProperties.PASSWORD_OR_TOKEN})
    public JenkinsServer jenkinsServer(JenkinsProperties properties) throws URISyntaxException {
        return new JenkinsServer(new URI(properties.getServiceUri()), properties.getUsername(),
                properties.getPasswordOrToken());
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnBean({JenkinsServer.class})
    @ConditionalOnProperty(JenkinsSyncProperties.ENABLED)
    public JenkinsItemSynchronizer jenkinsItemSynchronizer(JenkinsServer server,
                                                           JenkinsProperties properties,
                                                           JenkinsSyncProperties syncProperties) {
        return new JenkinsItemSynchronizer(server, properties, syncProperties);
    }
}

